//本地存储搜索历史
function SearchStorage(){
    this.key = 'search';
    this.list = [];

    this.getList();
}
SearchStorage.prototype = {
    add: function(value){
        if(this.list.length === 0){
            localStorage.setItem(this.key, value);
            this.list.push(value);
        }else {
            var curList = this.list.filter((val) => {
                return val != value
            });
            curList.push(value);
            localStorage.setItem(this.key, curList.join(','));
            this.list = curList;
        }
    },
    clear: function(){
        localStorage.removeItem(this.key);
        this.list = [];
    },
    getList: function(){
        var arr = localStorage.getItem(this.key);
        if(arr){
            this.list = arr.split(',');
        }
        return this.list;
    }
};
var Search = new SearchStorage();

//搜索条件
var searchParam = {
    cPage: 1,
    pSize: 20,
    userId: USER.userId,
    keyWord: ''
};
/**
 * 搜索页面头部
 */
var SearchHeader = React.createClass({
    handleSearchClick: function(e){
        //根据输入内容搜索
        var value =  $(e.target).parent().find('input').val().trim();
        if(value.length > 0){
            //this.props.hideSearch();
            this.props.search(value);
        }
        e.stopPropagation();
        e.preventDefault();
    },
    handleSearchKeyUp: function(e){
        var event = e || window.event;
        var key = event.which || event.keyCode || event.charCode;
        if(key == 13){
            this.handleSearchClick(e);
        }
    },
    handleCancelClick: function(e){
        //已搜索过并有商品数据展示在页面中，隐藏搜索框
        //否则回到前一页，放弃搜索操作
        if(this.props.length > 0){
            this.props.hideSearch();
        }else {
            history.go(-1);
        }
        e.stopPropagation();
        e.preventDefault();
    },
    render: function() {
        return (
            <header data-am-widget="header" className="am-header am-header-default am-header-fixed ">
                <h1 className="am-header-title margin-left-35-right-35" >
                    <div className="search-1 ">
                        <input className="font-14" type="search" id="txtsearch" placeholder="请输入搜索关键字" maxLength="50" autoFocus onKeyUp={this.handleSearchKeyUp}/>
                        <i className="icon_searchgray" onClick={this.handleSearchClick}></i>
                    </div>
                </h1>
                <div className="am-header-right am-header-nav">
                    <a onClick={this.handleCancelClick}>取消</a>
                </div>
            </header>
        )
    }
});
/**
 * 搜索出的列表
 */
var SearchHeaderResult = React.createClass({
    render: function() {
        return (
            <header data-am-widget="header" className="am-header am-header-default am-header-fixed  am-no-layout">
                <div className="am-header-left am-header-nav box">
                    <a onClick={handleBackClick}><i className="icon_8"></i></a>
                </div>
                <h1 className="am-header-title margin-left-35-right-35" style={{'padding-left':'50px'}}>
                    <div className="search-1 ">
                        <input className="font-14" type="search" id="txtsearch" placeholder="请输入搜索关键字" onFocus={this.props.showSearch}/><i className="icon_searchgray"></i>
                    </div>
                </h1>
                
            </header>
        )
    }
});
/**
 * 最近搜索
 */
var SearchRecentPage = React.createClass({
    getInitialState: function(){
        return {
            searchList: Search.getList()
        }
    },
    //清空最近搜索
    handleClearClick: function(e){
        Search.clear();
        this.setState({
            searchList: Search.getList()
        });
        e.stopPropagation();
        e.preventDefault();
    },
    //点击最近搜索 搜索
    handleLabelSearchClick: function(e){
        var target = e.target;
        if(target.nodeName.toLowerCase() === 'a'){
            this.props.search(target.innerHTML);
            e.stopPropagation();
            e.preventDefault();
        }
    },
    render: function() {
        var searchItems = [], l = this.state.searchList.length;
        for(var i = l; i > 0 ;){
            searchItems.push(<li><a>{this.state.searchList[--i]}</a></li>);
        }
        return (
            <section data-tag="css-nav">
                <div className="bg-white am-margin-top-sm">
                    <div data-am-widget="titlebar" className="am-titlebar am-titlebar-default box prelative">
                        <i className="bgmainblock"></i>
                        <h2 className="am-titlebar-title box-1">最近搜索</h2>
                        <div className="font-color-1 font-14 am-padding-right-sm" onClick={this.handleClearClick}>清空</div>
                    </div>
                </div>
                <div className="am-padding-left-sm  bg-white am-cf border-tops am-padding-top-sm">
                    <div className="resou">
                        <ul onClick={this.handleLabelSearchClick}>{searchItems}</ul>
                    </div>
                </div>
            </section>
        )
    }
});
/**
 * 筛选面板
 */
var FilterBar = React.createClass({
    handleMenuClick: function(e){
        var target = e.target;
        if(target === e.currentTarget && target.className.indexOf('tab-fixed') < 0){
            target.className += ' tab-fixed';
            e.stopPropagation();
            e.preventDefault();
        }
    },
    handleSalesSearchClick: function(e){
        //searchParam TODO 销量
        this.props.search();
        e.stopPropagation();
        e.preventDefault();
    },
    handlePriceSearchClick: function(e){
        //searchParam TODO 价格
        this.props.search();
        e.stopPropagation();
        e.preventDefault();
    },
    render: function(){
        return(
            <div className="am-g am-g-collapse expert_tabs bg-white am-text-center border-bottom padding-top-bottom-10 font-15 font-color-2 tab-fixed filter_menu" onClick={this.handleMenuClick}>
                <div className="am-u-sm-4 "><a id="secure_fenlei" className="prelative" onClick={this.handleSalesSearchClick}>销量</a></div>
                <div className="am-u-sm-4 "><a id="secure_paixu" className="prelative" onClick={this.handlePriceSearchClick}>价格<span className="am-icon-long-arrow-down am-margin-left-xs sort font-12"></span></a></div>
                <div className="am-u-sm-4 "><a className="prelative" id="secure_shaixuan">筛选<span className="am-icon-angle-down margin-left-5"></span></a></div>
            </div>
        )
    }
});
//搜索分类项目名
var FilterPanelLabel = React.createClass({
    render: function(){
        return (
            <div className="bg-white border-bottom" >
                <div data-am-widget="titlebar" className="am-titlebar am-titlebar-default box prelative" >
                    <i className="bgmainblock"> </i>
                    <h2 className="am-titlebar-title box-1">{this.props.title}</h2>
                    <div className="font-color-1 font-14 am-padding-right-sm">更多<span className="am-icon-angle-down margin-left-5" ></span></div>
                </div>
            </div>
        )
    }
});
//搜索分类项目内容
var FilterPanelList = React.createClass({
    handleFilterClick: function(e) {
        var target = e.target;
        if(target.nodeName === 'A'){
            var $p = $(e.target).parent();
            $p.siblings("li").removeClass("am-active");
            $p.addClass("am-active");
        }
    },
    render: function(){
        var arr = [], list = this.props.types ? this.props.types : this.props.brands;
        list.forEach((value) => {
            arr.push(<li data-id={value.id}><a>{value.name}</a></li>);  //选中class am-active
        });
        return <div className="bg-white am-padding-top-xs" >
            <div className="am-padding-left-sm" >
                <ul onClick={this.handleFilterClick} className="tag am-pagination am-pagination-default hotsearch">
                    {arr}
                </ul>
            </div>
        </div>
    }
});
//筛选面板
var FilterPanel = React.createClass({
    getInitialState: function() {
        return {
            types: [],
            brands: [],
            prices: []
        }
    },
    componentWillMount: function() {
        $.ajax(
            getAjaxOps('/offer/initSerchCond')
        ).done(function (res){
            if(res.resultCode == 0){
                var arr = res.data.price.split(','),l = arr.length, prices = [],types = [],brands = [];
                for(var i = 0; i < l ; i++){
                    if(i === l-1){
                        prices.push([arr[i]]);
                    }else{
                        prices.push([arr[i], arr[i+1]]);
                    }
                }
                res.data.types.forEach(function(value){
                    types.push({
                        id: value.id,
                        name: value.offer_type_name
                    })
                });
                res.data.brands.forEach(function(value){
                    brands.push({
                        id: value.id,
                        name: value.brand_name
                    })
                });
                this.setState({
                    types: types,
                    brands: brands,
                    prices: prices
                })
            }
        }.bind(this));
    },
    handlePriceClick: function(e) {
        var target = e.target;
        if(target.nodeName === 'A'){
            var $p = $(target).parent();
            $p.siblings("li").removeClass("am-active");
            $p.addClass("am-active");
            //最高|最低价格填入input框
            var low = target.getAttribute('data-low'), high = target.getAttribute('data-high');
            var lowInput = ReactDOM.findDOMNode(this.refs.low),highInput = ReactDOM.findDOMNode(this.refs.high);
            lowInput.value = low;
            if(high){
                highInput.value = high;
            }else{
                highInput.value = '';
            }
            //e.stopPropagation();
            //e.preventDefault();
        }
    },
    handleClearCondClick: function(e) {
        //清空筛选条件
        //var actives = document.querySelectorAll('.am-active');
        //actives.forEach(function (el) {
        //    el.className = el.className.replace(/am-active/g,'');
        //});
        $('.am-active').removeClass('am-active');
        ReactDOM.findDOMNode(this.refs.low).value = '';
        ReactDOM.findDOMNode(this.refs.high).value = '';
        e.stopPropagation();
        e.preventDefault();
    },
    handleFilterSearchClick: function(e) {
        //根据筛选条件搜索  TODO
        //searchParam = ?

        //隐藏面板
        $(".filter-container").hide();
        $(".global-mask").hide();

        e.stopPropagation();
        e.preventDefault();
    },
    render: function() {
        var searchPriceArr = [];
        this.state.prices.forEach((value) => {
            if(value[1]){
                searchPriceArr.push(
                    <li><a data-low={value[0]} data-high={value[1]}>{value[0]+'-'+value[1]}</a></li>
                )
            }else{
                searchPriceArr.push(
                    <li><a data-low={value[0]} data-high=''>{value[0]+'以上'}</a></li>
                )
            }
        });
        return(
            <div className="filter-container" data-node="secure_shaixuan">
                <FilterPanelLabel title={'分类'} /><FilterPanelList types={this.state.types} />
                <FilterPanelLabel title={'分类'} /><FilterPanelList brands={this.state.brands} />
                <FilterPanelLabel title={'价格'} />
                <div className="bg-white am-padding-top-xs">
                    <div className="am-padding-left-sm ">
                        <ul className="tag am-pagination am-pagination-default hotsearch" onClick={this.handlePriceClick}>
                            {searchPriceArr}
                        </ul>
                    </div>
                </div>
                <div className="box bg-white am-padding-bottom-sm am-padding-left-lg am-padding-right-lg am-padding-top-sm">
                    <div><input type="tel" className="input-7" placeholder="最低价" ref="low"/></div>
                    <div className="box-1 font-color-1 am-text-center">--</div>
                    <div><input type="tel" className="input-7" placeholder="最高价" ref="high"/></div>
                </div>
                <div className="am-g bg-white am-padding-top-sm am-padding-bottom-sm">
                    <div className="am-u-sm-6">
                        <div className="order-btn-3 am-text-center" onClick={this.handleClearCondClick}>清空条件</div>
                    </div>
                    <div className="am-u-sm-6">
                        <div id="btnenter" className="order-btn-2 am-text-center" onClick={this.handleFilterSearchClick}>确定</div>
                    </div>
                </div>
            </div>
        )
    }
});
/**
 * 商品列表
 * 搜索|筛选结果
 */
var GoodsItem = React.createClass({
    handleSearchRecentClick: function(){
        location.href='detail.html?goodId='+this.props.data.id;
    },
    render: function() {
        var goods = this.props.data;
        return (
            <div className="box-1 am-margin-right-sm prelative">
                <div onClick={this.handleSearchRecentClick} className="goodpic">
                    <img className="width-100" src={IMG_PRE+goods.url} /><i className="icon-cuxiao"></i>
                </div>
                <div className="am-margin-top-xs font-color-11 am-text-truncate">{goods.offer_name}</div>
                <div className="am-g am-g-collapse am-margin-top-xs">
                    <div className="am-u-sm-12 ">
                        <div className="box">
                            <div className="box-1 font-color-monney">
                                <div className="line20px"><span>&yen;</span><span className="font-18 margin-left-2">{goods.flag!=0 ? goods.out_price.toPrice() : goods.in_price.toPrice()}</span></div>
                                <div className=""><span className="font-color-1 font-12">已售{goods.saleCnt}</span></div>
                            </div>
                            <div className="am-margin-right-xs">
                                <div className={'my-icon-guanzhu' + (goods.keep == 1 ? ' cur' : '')} data-id={goods.id}></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
});
//搜索结果列表
var GoodsList = React.createClass({
    handleHeartClick: function(e) {
        var target = e.target, cName = target.className;
        if(target !== e.currentTarget && cName.indexOf('my-icon-guanzhu') >= 0 && ifUser()){
            var param = {
                userId: USER.userId,
                offerId: target.getAttribute('data-id')
            };
            if(cName.indexOf('cur') >= 0){
                $.ajax(
                    getAjaxOps('/offer/addKeep', param)
                ).done(function(res) {
                        if(res.resultCode == 0){
                            target.className = cName.replace(/cur/g, '');
                        }
                    });
            }else{
                $.ajax(
                    getAjaxOps('/offer/removeKeep', param)
                ).done(function(res) {
                        if(res.resultCode == 0){
                            target.className = cName + ' cur';
                        }
                    });
            }
        }
    },
    render: function() {
        var goodsItemsArr = [], l = this.props.goodsList.length;
        for(var i = 0; i < l; i += 2){
            if(i === (l-1)){
                goodsItemsArr.push(
                    <div className="item am-margin-bottom-sm">
                        <div className="box">
                            <GoodsItem data={this.props.goodsList[i]}/>
                        </div>
                    </div>
                );

            }else{
                goodsItemsArr.push(
                    <div className="item am-margin-bottom-sm">
                        <div className="box">
                            <GoodsItem data={this.props.goodsList[i]}/>
                            <GoodsItem data={this.props.goodsList[i+1]} />
                        </div>
                    </div>
                );
            }
        }
        if(this.props.isLast){
            //最后一页
            goodsItemsArr.push(
                <div className="item am-margin-bottom-sm">
                    <div className="box">
                        <div className="goods-no-more"><p>没有更多数据了</p></div>
                    </div>
                </div>
            )
        }
        return(
            <div onClick={this.handleHeartClick} className="list am-padding-top-sm bg-white am-padding-left-sm ">
                {goodsItemsArr}
            </div>
        )
    }
});
var SearchResultPage = React.createClass({
    render: function() {
        //<FilterBar search={this.props.search} />
        //<FilterPanel />
        return (
            <section data-tag="css-nav">
                <div className="global-mask"></div>
                <GoodsList isLast={this.props.isLast} goodsList={this.props.goodsList}/>
            </section>
        )
    }
});

var dataList = [];
var Page = React.createClass({
    getInitialState: function() {
        return{
            isInputFocused: true, //搜索框是否激活
            isLast: false, //商品是否搜索至最后一页
            isLoading: false, //是否正在加载
            goodsList: []   //结果商品列表
        }
    },
    componentDidMount: function() {
        window.onscroll = this.load;
    },
    load: function() {
        if(!this.state.isLoading && (getClientHeight() + getDocumentTop() >= getScrollHeight())){
            this.search();
        }
    },
    showSearch: function() {
        this.setState({
            isInputFocused: true
        });
    },
    hideSearch: function() {
        this.setState({
            isInputFocused: false
        })
    },
    search: function(value) {
        if(value){
            searchParam.keyWord = value;
            Search.add(value);
        }else if(this.state.isLast){
            return false;
        }
        this.setState({
            isInputFocused: false,
            isLoading: true
        });
        $.ajax(
            getAjaxOps('/offer/qryOfferListByKeyWords', searchParam)
        ).done(function (res) {
            if(res.resultCode == 0){
                this.setState({
                    isLoading: false
                });
                if(value){
                    dataList = res.data.list;
                }else {
                    Array.prototype.push.apply(dataList, res.data.list);//当前页面数据添加进商品列表
                }
                this.setState({
                    goodsList: dataList
                });
                if(!res.data.lastPage){
                    searchParam.cPage++;
                }else{
                    //最后一页
                    this.setState({
                        isLast: true
                    })
                }
            }
        }.bind(this));
    },
    render: function() {
        if(this.state.isInputFocused){
            return (
                <div>
                    <SearchHeader length={this.state.goodsList.length} search={this.search} hideSearch={this.hideSearch}/>
                    <SearchRecentPage search={this.search} />
                </div>
            )
        }else {
            return (
                <div>
                    <SearchHeaderResult showSearch={this.showSearch}/>
                    <SearchResultPage search={this.search} isLast={this.state.isLast} goodsList={this.state.goodsList}/>
                </div>
            )
        }
    }
});

ReactDOM.render(
    <Page />,
    document.getElementById('root')
);

